package com.jinyi.wwdeng.ui.steps.fragment

import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jinyi.base.utils.log.HHLog
import com.jinyi.wwdeng.App
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.databinding.FragmentStepCommonBinding
import com.jinyi.wwdeng.network.HttpBaseParams.addCommonParams
import com.jinyi.wwdeng.pro.ProFragment
import com.jinyi.wwdeng.ui.steps.act.StepListAct
import com.jinyi.wwdeng.ui.steps.adapter.StepContactInfoAdapter
import com.jinyi.wwdeng.utils.StringDeepCopy
import com.jinyi.wwdeng.utils.event.TrackEventType
import com.jinyi.wwdeng.utils.event.TrackEventUtils
import com.jinyi.wwdeng.utils.recyclerview.LinearSpacingItemDecoration
import org.json.JSONArray
import org.json.JSONObject

/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/18 11:29
 * @Annotation：流程 - 联系人信息
 */
class StepContactFragment(val data: JSONObject): ProFragment() {
    lateinit var binding: FragmentStepCommonBinding
    //内容列表
    var mContactAdapter: StepContactInfoAdapter? = null

    override fun getRootView(inflater: LayoutInflater): View {
        binding = FragmentStepCommonBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        initRecyclerView()
    }

    override fun initListener() {
        //下一步
        binding.btnNext.setOnClickListener {
            if (!isAllowSubmit()){
                showToast(getString(R.string.submit_error))
                return@setOnClickListener
            }
            val params = JSONObject().addCommonParams().apply {
                put("path",data.optString("apiUrl").replace("/",""))
            }
            //拼接上传数据格式
            val paramArray = JSONArray()
            for (i in 0..<mContactAdapter!!.itemCount){
                val obj = JSONObject()
                val dataArray = mContactAdapter!!.getItem(i).optJSONArray("dataList")
                for (j in 0..<dataArray!!.length()){
                    val item = dataArray.optJSONObject(j)
                    obj.put(item.optString("paramName"),item.optJSONObject("selectItem").optString("value"))
                }
                paramArray.put(obj)
            }
            params.put(data.optString("contactParamName"),paramArray)
            HHLog.e(">>>>>>提交联系人数据>>>>>>>"+params)
            val act = context as StepListAct
            act.onSubmitRequest(params)

            TrackEventUtils.logEvent(String.format(TrackEventType.CLICK.CLICK_STEP_XX_NEXT,data.optString("stepTitle")),"")
        }
    }

    override fun initData() {
        // TODO: 这里dataList需要深拷贝，否则列表会共用一个数据源
        val stringCopy = StringDeepCopy(data.optString("dataList"))
        val dataList = arrayListOf<JSONObject>()
        for (i in 0..<data.optInt("itemCount")){
            val obj = JSONObject()
            obj.put("brandTitle",getString(R.string.contact)+(i+1).toString())
            val dataArray = JSONArray(stringCopy.content)
            for (j in 0..<dataArray.length()){
                val dataObj = dataArray.optJSONObject(j)
                dataObj.put("title",dataObj.optString("title"))
                when(dataObj.optString("action")){
                    "CONTACT_GROUP_RELATION",
                    "SELECT" -> {
                        dataObj.put("action","SELECT")
                        val valueArray = data.optJSONArray("relationShips").optJSONArray(i)
                        val values = JSONArray()
                        for (n in 0..<valueArray.length()){
                            val value = JSONObject()
                            value.put("title",valueArray.optString(n))
                            value.put("value",valueArray.optString(n))
                            values.put(value)
                        }
                        dataObj.put("values",values)
                    }
                    else -> {
                        dataObj.put("action","INPUT")
                    }
                }
            }
            obj.put("dataList",dataArray)
            dataList.add(obj)
        }
        mContactAdapter!!.data = dataList
    }

    /**
     * 初始化页面内容列表
     */
    private fun initRecyclerView() {
        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.recyclerView.layoutManager = layoutManager
        val topDecoration = App.dp2px(14f)
        binding.recyclerView.addItemDecoration(LinearSpacingItemDecoration(0,0,0,topDecoration))
        mContactAdapter = StepContactInfoAdapter(binding.recyclerView)
        mContactAdapter!!.parentView = binding.root
        binding.recyclerView.adapter = mContactAdapter!!
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
    }

    /**
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowSubmit(): Boolean{
        val dataList = arrayListOf<JSONObject>()
        for (i in 0..<mContactAdapter!!.itemCount){
            val dataArray = mContactAdapter!!.getItem(i).optJSONArray("dataList")
            for (j in 0..<dataArray!!.length()){
                val item = dataArray.optJSONObject(j)
                dataList.add(item)
            }
        }
        //是否允许提交
        var isAllow = true
        for (i in 0..<dataList.size){
            val item = dataList[i]
            //存在 isMust && isMust == ”NO“  非必填
            if (item.has("isMust") && item.optString("isMust") == "NO"){
                continue
            }
            //必填 && 没有内容 || 内容为空
            if (!item.has("selectItem") || item.optJSONObject("selectItem")?.optString("value")!!.isEmpty()){
                isAllow = false
                break
            }
        }
        return isAllow
    }

    override fun onStart() {
        super.onStart()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_STEP_CONTACT_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_STEP_CONTACT_END,"")
    }
}